﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Text;
using System.Xml.Linq;
using System.Data;
using System.Net;
using System.Web.Script.Serialization;
using Cms.Common;

public partial class shop_newUser : System.Web.UI.Page
{
    public class SmsApi
    {

        public string rescode { get; set; }

        public string message { get; set; }

    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            string redirectUrl = Request.Url.ToString();
            Cms.BLL.wx_info info = new Cms.BLL.wx_info();
            string appid = info.GetModel(1).AppId;
            string appsecret = info.GetModel(1).AppSecret;
            DropList_Bind();
            if (Request.QueryString["code"] != null && Request.QueryString["code"] != "")
            {

                string Code = Request.QueryString["code"].ToString();
                string result = wxuserinfo.getwxCode(Code, redirectUrl);
                HiddenField1.Value = result;
                Session["user_openid"] = result;
            }
            else
            {
                string posturl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect ";
                Response.Redirect(posturl);
            }
        }
    }

    #region 绑定门店=================================
    public void DropList_Bind()
    {
        //parentId.Items.Clear();
        List<wxuser.ShopInfo> list = new List<wxuser.ShopInfo>();

        list = wxuser.getShopInfo("ok");
        if (list != null && list.Count > 0)
        {
            for (int i = 0; i < list.Count; i++)
            {

                ListItem item = new ListItem();
                item.Text = list[i].shopname.ToString();
                item.Value = list[i].shopcode.ToString();
                parentId.Items.Add(item);
            }

        }

    }

    #endregion

    #region 发送短信==============
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        this.Session["Verification_code"] = Cms.Common.Utils.Number(6);//随机生成6位数字
        string telphone = telPhone.Value.Trim();
        string content = "您当前的手机验证码：" + this.Session["Verification_code"].ToString();

        Cms.BLL.C_sms bll = new Cms.BLL.C_sms();
        Cms.Model.C_sms model = new Cms.Model.C_sms();
        model.name = "";//名字
        model.telphone = telphone;//手机号码
        model.content = content;//内容
        model.state = 0;//发送状态
        model.updateTime = Convert.ToDateTime(Cms.Common.ManagementInfo.GetTime());//时间
        int result = bll.Add(model);
        if (result > 0)
        {
            string smsResult = adminUser.Sms(telphone, content);
            SmsApi p = Cms.Common.Utils.JsonDeserialize<SmsApi>(smsResult);
            if (p.rescode == "0")
            {
                int counts = Cms.DBUtility.DbHelperSQL.ExecuteSql("update C_sms set state=1 where id=" + result);//修改状态
                //JscriptMsg("验证码发送成功！", "NotJump", "Success");
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "parent.jsprintWeb(\"验证码发送成功！\", \"NotJump\", \"Success\")", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "parent.jsprintWeb(\"验证码发送失败！\", \"NotJump\", \"Error\")", true);
                //JscriptMsg("验证码发送失败！", "NotJump", "Error");
            }
        }
    }
    #endregion


    #region 开通新会员=======================
    protected void Button1_Click(object sender, EventArgs e)
    {
        Cms.BLL.C_user cuser = new Cms.BLL.C_user();
        Cms.Model.C_user muser = new Cms.Model.C_user();
        string tel_phone = telPhone.Value.Trim();
        if (cuser.Exists(tel_phone))
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"该手机号已经注册过！\", \"NotJump\", \"Error\")", true);
            //JscriptMsg("该手机号已经注册过！", "NotJump", "Error");
            return;
        }
        if (this.Session["Verification_code"].ToString() != VerificationCode.Value.Trim())
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"验证码不正确！\", \"NotJump\", \"Error\")", true);
            //JscriptMsg("验证码不正确！", "NotJump", "Error");
            return;
        }
        if (agree.Checked == false)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"请同意《DBE会员章程》！\", \"NotJump\", \"Error\")", true);
            //JscriptMsg("请同意《DBE会员章程》！", "NotJump", "Error");
            return;
        }
        if (Cms.DBUtility.DbHelperSQL.Exists("select count(1) from wx_userinfo where openid='" + HiddenField1.Value + "'"))
        {
            DataTable dt = new Cms.BLL.wx_userinfo().GetList("openid='" + HiddenField1.Value + "'").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                muser.username = dt.Rows[0]["nickname"].ToString();
                muser.sex = dt.Rows[0]["sex"].ToString() == "1" ? "M" : "W";
                muser.useraddress = dt.Rows[0]["country"].ToString() + dt.Rows[0]["province"].ToString() + dt.Rows[0]["city"].ToString();
                muser.headimgurl = dt.Rows[0]["headimgurl"].ToString();
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"请关注DBE珠宝微信公众号！\", \"NotJump\", \"Error\")", true);
            return;
        }
        string usercard = wxuser.getusercard();
        muser.telphone = tel_phone;
        muser.password = "123456";
        muser.birthday = DateTime.Now;
        muser.marryday = DateTime.Now;
        muser.latitude = "";
        muser.longitude = "";
        muser.isbind = 1;
        muser.isSign = 1;
        muser.userYesScore = 0;
        muser.userallscore = 0;
        muser.userscore = 0;
        muser.userMoney = Convert.ToDecimal("0.00");
        muser.usercard = "";
        muser.shopname = parentId.SelectedItem.Text.ToString();
        muser.shopcode=parentId.SelectedValue.ToString();
        string Code = Request.QueryString["code"].ToString();
        muser.openid = Session["user_openid"].ToString();
        muser.updatetime = DateTime.Now;
        try{
        int result = cuser.Add(muser);
        if (result > 0)
        {

            //设置同步到CRM更新会员
            wxuser.UserSale wu = new wxuser.UserSale();
            wxuser.userinfo xw = new wxuser.userinfo();
            xw = wxuser.getuserinfo(muser.openid);
            if (xw.result == "获取失败")
            {
                wu = wxuser.getUserRegister(muser.openid, muser.username, muser.sex, muser.useraddress, string.Format("{0:yyyy-MM-dd}", muser.birthday), string.Format("{0:yyyy-MM-dd}", muser.marryday), muser.telphone, muser.shopcode);
                //Literal1.Text = wu.content + "-" + wu.result + "-" + wu.usercard;
                xw = wxuser.getuserinfo(muser.openid);
                muser = cuser.GetModel(result);
                muser.usercard = xw.usercard;
                muser.userallscore = Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userallscore)).ToString());
                muser.userscore = Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userscore)).ToString());
                muser.userYesScore = Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userallscore)).ToString()) - Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userscore)).ToString());
                muser.userlevel = xw.userlevel;
                muser.shopname = xw.shopname;
                cuser.Update(muser);
            }
            else
            {
                muser = cuser.GetModel(result);
                muser.usercard = xw.usercard;
                muser.userallscore = Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userallscore)).ToString());
                muser.userscore = Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userscore)).ToString());
                muser.userYesScore = Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userallscore)).ToString()) - Convert.ToInt32(Math.Round(Convert.ToDecimal(xw.userscore)).ToString());
                muser.userlevel = xw.userlevel;
                muser.shopname = xw.shopname;
                cuser.Update(muser);
            }

            //写入session
            Session["user_id"] = result;//保存session 用户ID
            //写入Cookie
            HttpCookie cookie = new HttpCookie("user");//创建Cookie
            cookie["user_id"] = result.ToString();//保存Cookie 用户ID
            cookie.Expires = DateTime.Now.AddHours(14400);
            Response.Cookies.Add(cookie);
            adminUser.AddUserLog(Cms.Common.DTEnums.ActionEnum.Login.ToString(), "用户注册");
            Response.Redirect("/shop/main.aspx");
        }
        else
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "JsPrint", "jsprintWeb(\"开通失败！\", \"NotJump\", \"Error\")", true);
        }
        }
        catch (Exception ex)
            {
                Response.Write(ex.Message);
                
            }
        
    }
    #endregion

    #region 提示框=================================
    public void JscriptMsg(string msgtitle, string url, string msgcss)
    {
        string msbox = "";
        if (url == "back")
        {
            msbox = "parent.jsdialog(\"提示\", \"" + msgtitle + "\",\"" + url + "\", \"\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }
        else
        {
            msbox = "parent.jsprintWeb(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }

    }
    #endregion
}